using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using OpenWaves.Reflection;

namespace OpenWaves.ActivityFeed.Web.Controls
{
    [ParseChildren(false)]
    [PersistChildren(true)]
    public class KnockoutJSTemplate : Control
    {
        public KnockoutJSTemplate()
        {
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(String.Format(CultureInfo.InvariantCulture, "<script id=\"{0}\" type=\"text/html\">", this.ClientID));
            
            if (RunningWithEPiServerFriendlyUrlProvider)
                writer.Write("<![CDATA[");

            base.RenderChildren(writer);

            if (RunningWithEPiServerFriendlyUrlProvider)
                writer.Write("]]>");
            
            writer.Write("</script>");
        }

        private static bool RunningWithEPiServerFriendlyUrlProvider
        {
            get
            {
                var global = Type.GetType("EPiServer.Global, EPiServer");
                if (global == null)
                    return false;

                var friendlyUrlProviderType = Type.GetType("EPiServer.Web.FriendlyUrlRewriteProvider, EPiServer");
                if (friendlyUrlProviderType == null)
                    return false;

                var urlRewriteProviderProperty = global.GetProperty("UrlRewriteProvider");
                if (urlRewriteProviderProperty == null)
                {
                    Log.Warning("Unable to access UrlRewriteProvider property on EPiServer.Global type to determine rendering variant of KnockoutJSTemplate. Assuming we're not running with EPiServerFriendlyUrlProvider.");
                    return false;
                }

                var urlRewriteProvieder = urlRewriteProviderProperty.GetValue(null, new object[0]);

                return friendlyUrlProviderType.IsInstanceOfType(urlRewriteProvieder);
            }
        }
    }
}